package com.yxsk.relay.job.admin.web.common.security;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yxsk.relay.job.admin.web.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 11376
 * @CreaTime 2019/6/26 10:25
 * @Description
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    private String[] ignoreUri;

    private PathMatcher pathMatcher;

    public LoginCheckInterceptor(String... ignoreUri) {
        this.ignoreUri = ignoreUri;
        this.pathMatcher = new AntPathMatcher("/");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        // 先查询是否属于忽略的 URI
        if (this.ignoreUri != null) {
            for (String patternUri : ignoreUri) {
                if (pathMatcher.match(patternUri, requestURI)) {
                    // 不拦截
                    return true;
                }
            }
        }
        // 校验 token
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (JwtUtil.TOKEN_NAME_OF_COOKIE.equals(cookie.getName())) {
                    String token = cookie.getValue();
                    try {
                        JwtUtil.verifyToken(token);
                        // token验证通过
                        return true;
                    } catch (JWTVerificationException e) {
                        // token错误
                    }
                }
            }
        }

        // 拦截请求
        try {
            response.sendRedirect("/login");
            return false;
        } catch (IOException e1) {
            log.error("", e1);
        }
        return false;
    }
}
